export default {
  data() {
    return {
      type: "add",
      operationName: {
        add: "添加",
        edit: "编辑",
        view: "查看"
      },
      elDialog: null
    };
  },
  watch: {
    "singleData.selectTime"(n) {
      if (n.length) {
        this.singleData.starttime = n[0];
        this.singleData.endtime = n[1];
      } else this.singleData.starttime = this.singleData.endtime = "";
    }
  },
  mounted() {
    this.elDialog = this.$refs.elDialog;
		this.singleData.examid=null
  },
  computed: {
    title() {
      return this.operationName[this.type] + this.moduleName;
    }
  },
  methods: {
    submit() {
      this.$refs["form"].validate(async valid => {
        if (valid) {
          //check the form successfully

          this.elDialog.$data.loading = true;
          if (typeof this.handle !== "function")
            throw "the component missing the “handle” function";

          //the handle resolve
          let res = await this.handle().catch(err => {
            // console.log("reject");
            // console.log(err);
          });
          if (res !== undefined) {
            res = res || {};
            const { end = true, ignore = false } = res;
            if (ignore) {
              this.elDialog.$data.loading = false;
              return;
            }
            //Global processing of edit and add request
            this.$notify.success(`操作成功！`);

            end && this.end(true);
          }
          this.elDialog.$data.loading = false;
        } else return false;
      });
    },
    checkFields(step, callback) {
      let validFieldsNum = 0;
      this.$refs.form.validateField(this.stepRule[step], valid => {
        if (valid) {
          callback(false);
          return false;
        } else validFieldsNum++;
      });
      callback(validFieldsNum === this.stepRule[step].length);
    },
    end(reload = false) {
      //end of interface calls
      this.elDialog.onClose();
      this.type = "add";
      this.$refs["form"].resetFields();
      reload && this.triggerOnReload();
    },
    setEditData(data) {
      this.type = "edit";
      this.$nextTick(() => {
        Object.keys(data).map(key => {
          this[key] = data[key];
        });
      });
    },
    triggerOnReload() {
      this.$emit("on-reload");
    }
  }
};
